const { sequelize } = require('../config/database');

async function migrateCreatorIdToCreatedBy() {
  try {
    // 检查是否已经存在createdBy字段
    const tableDescription = await sequelize.getQueryInterface().describeTable('parkpart_activities');
    
    if (!tableDescription.createdBy) {
      // 添加createdBy字段
      await sequelize.getQueryInterface().addColumn('parkpart_activities', 'createdBy', {
        type: sequelize.Sequelize.INTEGER,
        allowNull: false,
        references: {
          model: 'parkpart_users',
          key: 'id'
        }
      });
      
      // 将creatorId的值复制到createdBy
      await sequelize.query(`
        UPDATE parkpart_activities 
        SET createdBy = creatorId
      `);
      
      // 删除creatorId字段
      await sequelize.getQueryInterface().removeColumn('parkpart_activities', 'creatorId');
      
      // 添加createdBy索引
      await sequelize.getQueryInterface().addIndex('parkpart_activities', ['createdBy']);
      
      console.log('Migration completed successfully: creatorId -> createdBy');
    } else {
      console.log('createdBy field already exists, skipping migration');
    }
  } catch (error) {
    console.error('Migration failed:', error);
  }
}

// 如果直接运行此文件，则执行迁移
if (require.main === module) {
  migrateCreatorIdToCreatedBy().then(() => {
    console.log('Migration process completed');
    process.exit(0);
  }).catch(error => {
    console.error('Migration process failed:', error);
    process.exit(1);
  });
}

module.exports = migrateCreatorIdToCreatedBy;